<?php
namespace app\controller\admin;

use app\BaseController;
use app\lib\CacheKey;
use app\lib\response\JSON;
use app\model\Role as ModelRole;
use app\Request;
use app\validate\Role as RoleValidator;
use think\exception\ValidateException;
use think\facade\Cache;

class Role extends BaseController
{

    public function list()
    {
       $list = ModelRole::order('create_time','desc')->append(['is_super_role'])->paginate();
        return JSON::page($list->total(),$list->items());
    }

    public function all()
    {
        $list = ModelRole::order('create_time','desc')->field(['id','name'])->select();
        return JSON::successData(['list'=>$list]);
    }

    public function add(Request $r){
        $params = $r->post();
        try {
            validate(RoleValidator::class)
                ->scene('add')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        $exists = ModelRole::where('name',$params['name'])->value('id');
        if($exists){
            return JSON::error("角色名称已存在");
        }
        $role = new ModelRole();
        $role->name = $params['name'];
        $role->api_ids = array_unique($params['api_ids']);
        $role->desc = $params['desc'] ?? "";
        $role->save();
        return JSON::success("添加成功");

    }

    public function edit(Request $r){
        $params = $r->post();
        try {
            validate(RoleValidator::class)
                ->scene('edit')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        $exists = ModelRole::where('name',$params['name'])->where('id','<>',$params['id'])->value('id');
        if($exists){
            return JSON::error("角色名称已存在");
        }

        $role = ModelRole::findOrFail($params['id']);
        $role->name = $params['name'];
        $role->api_ids = array_unique($params['api_ids']);
        $role->desc = $params['desc'] ?? "";
        $role->save();
        Cache::delete(CacheKey::ROLE_API_PATH . $role->id);//删除角色的权限缓存
        return JSON::success("修改成功");

    }

    public function delete(Request $r){
        $params = $r->post();
        try {
            validate(RoleValidator::class)
                ->scene('delete')
                ->check($params);
        } catch (ValidateException $e) {
            return JSON::error($e->getMessage());
        }
        $hasRelated = \app\model\User::where('role_id',$params['id'])->find();
        if($hasRelated){
            return JSON::error("角色有用户关联，不能删除");
        }
        ModelRole::destroy($params['id']);
        return JSON::success("已删除");
    }

}
